package com.kzw.oa.system.service;

import org.hibernate.Hibernate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.oa.system.model.AppUser;

@Service("userDetailsService")
public class AppUserDetailsService extends DefaultEntityManager<AppUser, Long>
		implements UserDetailsService {

	@Override
	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		String hql = "from AppUser where username=?";
		AppUser user = getEntityDao().findUnique(hql, username);
		
		if (user == null) {
			 throw new UsernameNotFoundException(username);
		}
		
		Hibernate.initialize(user.getRoles());
		Hibernate.initialize(user.getDept());
		
		// 初始化用户信息
		user.init();
		
		return user;
	}

}
